<template>
  <div style="display: flex; gap: 8px">
    <OrderDishSelected
      ref="selectedRef"
      :desk="deskDetail"
      :mode="pageMode"
      :hasOrder="!!deskDetail?.order_id && deskDetail?.order_id !== '0'"
      @openPractice="onOpenPractice"
      @openTaste="onOpenTaste"
      @openPosition="onOpenPosition"
      @openSideDish="onOpenSideDish"
      @loadDeskBaseInfo="loadDeskBaseInfo"
    />
    <!-- 右侧面板：菜单 / 做法 / 口味 / 部位 / 配菜 -->
    <OrderDishMenu
      v-if="!showPracticePanel && !showTastePanel && !showPositionPanel && !showSideDishPanel"
      @selectFood="onPickFood"
      @back="onBack"
      @action="onRightAction"
      @selectCookBookFoods="onSelectCookBookFoods"
    />
    <OrderDishPracticePanel
      v-if="showPracticePanel"
      :currentFoodData="practiceFoodData"
      isUserLeaving.value="true"
      @back="onPracticeBack"
      @confirm="onPracticeConfirm"
    />
    <OrderDishTastePanel
      v-if="showTastePanel"
      :currentFoodData="tasteFoodData"
      @back="onTasteBack"
      @confirm="onTasteConfirm"
    />
    <OrderDishPositionPanel
      v-if="showPositionPanel"
      :currentFoodData="positionFoodData"
      @back="onPositionBack"
      @confirm="onPositionConfirm"
    />
    <OrderDishSideDishPanel
      v-if="showSideDishPanel"
      :currentFoodData="sideDishFoodData"
      @back="onSideDishBack"
      @pick="onSideDishPick"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted, computed } from 'vue'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import OrderDishSelected from './OrderDishSelected.vue'
import OrderDishMenu from './OrderDishMenu.vue'
import OrderDishPracticePanel from './OrderDishPracticePanel.vue'
import OrderDishTastePanel from './OrderDishTastePanel.vue'
import OrderDishPositionPanel from './OrderDishPositionPanel.vue'
import OrderDishSideDishPanel from './OrderDishSideDishPanel.vue'
import { fetchDeskDetail } from '@/api/desktop'

const deskDetail = ref<any>(null)
const loadingDesk = ref(false)
const selectedRef = ref<any>(null)
const route = useRoute()
const router = useRouter()

// 根据URL参数动态设置模式
const pageMode = computed(() => {
  return route.query.fromPage === 'appointmentPage' ? 'appointmentPage' : 'desktopPage'
})

// 用户离开状态管理
const isUserLeaving = ref(false)

// 做法面板相关状态
const showPracticePanel = ref(false)
const practiceFoodData = ref<any>(null)
// 口味面板相关状态
const showTastePanel = ref(false)
const tasteFoodData = ref<any>(null)
// 部位面板相关状态
const showPositionPanel = ref(false)
const positionFoodData = ref<any>(null)
// 配菜面板相关状态
const showSideDishPanel = ref(false)
const sideDishFoodData = ref<any>(null)
// 操作按钮已内聚到 OrderDishSelected.vue

const onPickFood = (food: any) => {
  console.log(food);
  selectedRef.value?.addFoodFromMenu(food)
}

const onSelectCookBookFoods = (foods: any[]) => {
  // 批量添加菜谱中的菜品
  foods.forEach(food => {
    console.log('原始菜谱数据:', food);
    
    // 将菜谱数据转换为与常规添加匹配的格式
    const convertedFood = {
      id: food.foodInfo.id,
      name: food.foodInfo.name,
      sub_name: food.foodInfo.name,
      images: food.foodInfo.images || [],
      skuList: [{
        id: food.id,
        price: food.price,
        member_price: food.member_price,
        unit: food.unit,
        num: food.foodInfo.num
      }],
      num: food.foodInfo.num,
      category_id: food.foodInfo.category_id || '',
      store_id: food.foodInfo.store_id || '',
      is_group: food.is_group,
      status: 10,
      is_delete: food.is_delete,
      is_weight: food.is_weight,
      create_time: new Date().toISOString().replace('T', ' ').substring(0, 19),
      update_time: new Date().toISOString().replace('T', ' ').substring(0, 19)
    };
    
    console.log('转换后的数据:', convertedFood);
    onPickFood(convertedFood);
  })
}

const onBack = () => {
  if (pageMode.value === 'appointmentPage') {
    // 预约模式：保存选择的菜品并返回预订页面
    handleReturnToBookDialog()
  } else {
    // 普通模式：返回首页
    router.replace({ path: '/home/food/' + router.currentRoute.value.params.id })
  }
}

// 处理返回预订弹框的逻辑
const handleReturnToBookDialog = () => {
  // 返回预订页面
  router.replace({ path: '/book' })
}

const onOpenPractice = (foodData: any) => {
  // 仅打开做法面板，关闭其他面板
  showTastePanel.value = false
  showPositionPanel.value = false
  showSideDishPanel.value = false
  practiceFoodData.value = foodData
  showPracticePanel.value = true
}
const onOpenTaste = (foodData: any) => {
  // 仅打开口味面板，关闭其他面板
  showPracticePanel.value = false
  showPositionPanel.value = false
  showSideDishPanel.value = false
  tasteFoodData.value = foodData
  showTastePanel.value = true
}
const onOpenPosition = (foodData: any) => {
  // 仅打开部位面板，关闭其他面板
  showPracticePanel.value = false
  showTastePanel.value = false
  showSideDishPanel.value = false
  positionFoodData.value = foodData
  showPositionPanel.value = true
}
const onOpenSideDish = (foodData: any) => {
  // 仅打开配菜面板，关闭其他面板
  showPracticePanel.value = false
  showTastePanel.value = false
  showPositionPanel.value = false
  sideDishFoodData.value = foodData
  showSideDishPanel.value = true
}
const onRightAction = (type: string) => {
  /* TODO: 打开菜谱等 */
}

// 做法面板相关方法
const onPracticeBack = () => {
  showPracticePanel.value = false
  practiceFoodData.value = null
}

const onPracticeConfirm = (payload: { making_ids: number[]; write_making: any[] }) => {
  selectedRef.value?.onPrePracticeConfirm(payload)
  showPracticePanel.value = false
  practiceFoodData.value = null
}

// 口味面板相关方法
const onTasteBack = () => {
  showTastePanel.value = false
  tasteFoodData.value = null
}

const onTasteConfirm = (payload: {
  taste_ids: number[]
  write_taste: string[]
  selectedNames?: string[]
}) => {
  selectedRef.value?.onPreTasteConfirm && selectedRef.value.onPreTasteConfirm(payload)
  showTastePanel.value = false
  tasteFoodData.value = null
}

// 部位面板相关方法
const onPositionBack = () => {
  showPositionPanel.value = false
  positionFoodData.value = null
}

const onPositionConfirm = (payload: { position: string[]; selectedNames?: string[] }) => {
  selectedRef.value?.onPrePositionConfirm && selectedRef.value.onPrePositionConfirm(payload)
  showPositionPanel.value = false
  positionFoodData.value = null
}

// 配菜面板相关方法
const onSideDishBack = () => {
  showSideDishPanel.value = false
  sideDishFoodData.value = null
}
const onSideDishPick = (food: any) => {
  // 直接复用组件左侧 addFoodFromMenu 的逻辑新增一条
  selectedRef.value?.addFoodFromMenu && selectedRef.value.addFoodFromMenu(food)
  showSideDishPanel.value = false
  sideDishFoodData.value = null
}

const loadDeskBaseInfo = async () => {
  try {
    loadingDesk.value = true
    const id = (route.params.id as any) || (route.query.id as any)
    if (!id) return
    
    // 预约模式下不调用桌台详情接口，而是从本地存储获取预订数据
    if (pageMode.value === 'appointmentPage') {
      return
    }
    
    const deskRes: any = await fetchDeskDetail({ record_id: id })
    if (deskRes?.status === 200) {
      deskDetail.value = deskRes.data
    }
  } finally {
    loadingDesk.value = false
  }
}

onMounted(() => {
  loadDeskBaseInfo()
})

watch(
  () => [route.params.id, route.query.id],
  () => {
    loadDeskBaseInfo()
  }
)

// 路由前置拦截 - 用户离开页面时的处理
onBeforeRouteLeave((to, from, next) => {
  if (pageMode.value === 'appointmentPage') {
    return next()
  }
  selectedRef.value?.handleBackSend(
    deskDetail.value?.id?.toString() || deskDetail.value?.record_id?.toString(),
    next
  )
})

// 清理事件监听器
onUnmounted(() => {
  // handleExitCleanup()
})
</script>

<style scoped></style>
